package com.example.dangerouscargodriver.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.controller.EnterPlatformInfoController;
import com.example.dangerouscargodriver.controller.UserInfoController;
import com.example.dangerouscargodriver.entry.CompanyInfo;
import com.example.dangerouscargodriver.entry.ResourceDetailInfo;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.utils.TextUtils;
import com.example.dangerouscargodriver.widget.ActionBar;
import com.example.dangerouscargodriver.R;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.constants.ConstantsAPI;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;

public class OrderNowActivity extends HttpRequestActivity implements View.OnClickListener, IWXAPIEventHandler {

    private static final String TAG = "OrderNowActivity";
    private ActionBar mActionBar = null;
    private TextView mProtocol = null;

    private Button mOrderNow = null;
    private TextView mNeedHD = null;
    private TextView mNeedFP = null;
    private boolean mHDContain = false;
    private boolean mFPContain = false;
    private EditText mOrderMark = null;

    private CheckBox mGentleman = null;
    private CheckBox mLady = null;

    private EditText mContact = null;
    private EditText mMobilephone = null;
    private int mSex = 1;
    private boolean mProtocolAgreed = false;

    //
    ResourceDetailInfo mResourceInfo = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.initHttpComponent(OrderNowActivity.class);
        setContentView(R.layout.activity_order_now);
        mResourceInfo = (ResourceDetailInfo) getIntent().getSerializableExtra("info");
        mOrderNow = findViewById(R.id.btn_order_now);
        mOrderNow.setOnClickListener(this);
        mProtocol = findViewById(R.id.tv_protocol);
        TextUtils.getBuilder().click(getResources().getString(R.string.company_partner_protocol_order), getResources().getColor(R.color.liji_c_blue), new TextUtils.OnClickListener() {
            @Override
            public void onClick(int position) {
                Intent intent = new Intent(OrderNowActivity.this, ShowHtmlActivity.class);
                switch (position){
                    case 0:
                        intent.putExtra("type", "3");
                        break;
                    case 1:
                        intent.putExtra("type", "2");
                        break;
                    case 2:
                        intent.putExtra("type", "1");
                        break;
                }
                startActivity(intent);
            }
        }, "《危司机用户服务协议》", "《危司机隐私政策》", "《危司机平台订金担保规则》").checkBox(this,  mProtocol, new TextUtils.OnImageClickListener() {
            @Override
            public void onChecked() {
                //ToastUtils.showShortToast(BindingCardActivity.this, "checked");
                mProtocolAgreed = true;
            }

            @Override
            public void onUnChecked() {
                //ToastUtils.showShortToast(BindingCardActivity.this, "unChecked");
            }
        }).clickInto(mProtocol);

        mNeedHD = findViewById(R.id.tv_need_hd);
        mNeedFP = findViewById(R.id.tv_need_fp);
        mNeedHD.setOnClickListener(this);
        mNeedFP.setOnClickListener(this);
        mOrderMark = findViewById(R.id.ed_order_mark);

        mGentleman = findViewById(R.id.ck_gentleman);
        mGentleman.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    mLady.setChecked(false);
                    mSex = 1;
                }
                else{
                    mLady.setChecked(true);
                }
            }
        });
        mLady = findViewById(R.id.ck_lady);
        mLady.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked){
                    mGentleman.setChecked(false);
                    mSex = 0;
                }
                else{
                    mGentleman.setChecked(true);
                }
            }
        });

        mContact = findViewById(R.id.ed_contact);
        mMobilephone = findViewById(R.id.ed_mobilephone);

        if(UserInfoController.Instance().getUserInfo() != null){
            mMobilephone.setText(UserInfoController.Instance().getUserInfo().getMobilephone());
        }

        mActionBar = findViewById(R.id.actionBarOrderNow);
        mActionBar.setOnBackClickListener( new View.OnClickListener(){

            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private boolean checkUserInput(){
        if(mContact.getText().toString().equals("") ||
                mMobilephone.getText().toString().equals("")){
            ToastUtils.showLongToast(this, "请填写完整的联系信息！");
            return false;
        }
        else if(!mProtocolAgreed){
            ToastUtils.showLongToast(this, "请先同意相关的服务协议！");
            return false;
        }
        else {
            return true;
        }
    }

    private void executeOrderAction(){
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("token", AuthController.Instance().getToken());

        JSONObject param = new JSONObject();

        JSONObject attach = new JSONObject();
        try {
            param.put("type", 2);
            if(EnterPlatformInfoController.Instance().getEnterStatus() == EnterPlatformInfoController.ENTER_STATUS_COMPANY) {
                List<CompanyInfo> companyInfo = EnterPlatformInfoController.Instance().getCompanyInfoList();
                param.put("cid", companyInfo.get(1).getCid());
            }
            else{
                param.put("tid", EnterPlatformInfoController.Instance().getTid());
            }
            param.put("relevant_sign", "0");
            param.put("pay_fee", mResourceInfo.getDeposit());

            if(EnterPlatformInfoController.Instance().getEnterStatus() == EnterPlatformInfoController.ENTER_STATUS_COMPANY) {
                List<CompanyInfo> companyInfo = EnterPlatformInfoController.Instance().getCompanyInfoList();
                attach.put("sr_cid", companyInfo.get(1).getCid());
            }
            else{
                attach.put("sr_tid", EnterPlatformInfoController.Instance().getTid());
            }
            if(mResourceInfo != null) {
                attach.put("sg_id", mResourceInfo.getRecid());
                attach.put("total", mResourceInfo.getExpected_price());
            }
            attach.put("type", "2");
            attach.put("name", mContact.getText().toString());
            attach.put("mobilephone", mMobilephone.getText().toString());
            attach.put("sex", mSex);
            attach.put("remark", mOrderMark.getText().toString());
            param.put("attach", attach);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        sendHttpJsonRequest(
                RemoteAPI.REQUEST_V1_MAKE_PRE_ORDER,
                header,
                param,
                RemoteAPICmd.REQUEST_V1_MAKE_PRE_ORDER);
    }

    private void executeOrderActionNoDeposit(){
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("token", AuthController.Instance().getToken());

        JSONObject param = new JSONObject();

        JSONObject attach = new JSONObject();
        try {
            //param.put("openid", "og7AI0RrSYHvrujSVhxr7_X-Zsoc");
            param.put("openid", "0");
            param.put("type", 2);
            if(EnterPlatformInfoController.Instance().getEnterStatus() == EnterPlatformInfoController.ENTER_STATUS_COMPANY) {
                List<CompanyInfo> companyInfo = EnterPlatformInfoController.Instance().getCompanyInfoList();
                param.put("cid", Integer.parseInt(companyInfo.get(0).getCid()));
            }
            else{
                param.put("tid", EnterPlatformInfoController.Instance().getTid());
            }
            param.put("relevant_sign", 0);
            param.put("pay_fee", mResourceInfo.getDeposit());
            param.put("pay_port", "2");
            param.put("pay_port_desc", "4");

            if(EnterPlatformInfoController.Instance().getEnterStatus() == EnterPlatformInfoController.ENTER_STATUS_COMPANY) {
                List<CompanyInfo> companyInfo = EnterPlatformInfoController.Instance().getCompanyInfoList();
                attach.put("sr_cid", Integer.parseInt(companyInfo.get(1).getCid()));
            }
            else{
                attach.put("sr_tid", EnterPlatformInfoController.Instance().getTid());
            }
            if(mResourceInfo != null) {
                attach.put("sg_id", mResourceInfo.getRecid());
                attach.put("total", mResourceInfo.getExpected_price());
            }
            attach.put("type", "2");
            attach.put("name", mContact.getText().toString());
            attach.put("mobilephone", mMobilephone.getText().toString());
            attach.put("sex", mSex);
            if(!mOrderMark.getText().toString().equals("")) {
                attach.put("remark", mOrderMark.getText().toString());
            }
            param.put("attach", attach);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        sendHttpJsonRequest(
                RemoteAPI.REQUEST_V1_MAKE_PAY_RECORD,
                header,
                param,
                RemoteAPICmd.REQUEST_V1_MAKE_PAY_RECORD);
    }

    @Override
    protected void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            if(actionId == RemoteAPICmd.REQUEST_V1_MAKE_PRE_ORDER){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    ToastUtils.showLongToast(this, res.getString("message"));
                    String appId = "wxd152fb597ed45fa3"; // 填移动应用(App)的 AppId，非小程序的 AppID
                    IWXAPI api = WXAPIFactory.createWXAPI(getBaseContext(), appId);

                    WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
                    req.userName = "gh_a4f9e4e5a3fa"; // 填小程序原始id
                    ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
                    req.path = "pages/receive/receive?pre_order_key=" + res.getJSONObject("data").getString("pre_order_key");
                    req.miniprogramType = WXLaunchMiniProgram.Req.MINIPROGRAM_TYPE_PREVIEW;// 可选打开 开发版，体验版和正式版
                    api.sendReq(req);
                }
            }
            else if(actionId == RemoteAPICmd.REQUEST_V1_MAKE_PAY_RECORD){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                ToastUtils.showLongToast(this, res.getString("message"));
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    Intent intent = new Intent(this, OrderSuccessActivity.class);
                    intent.putExtra("id", res.getJSONObject("data").getString("o_id"));
                    startActivity(intent);
                    finish();
                }
            }
            else{

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {
        if(actionId == RemoteAPICmd.REQUEST_V1_MAKE_PRE_ORDER){
            noticeOffline();
        }
        else if(actionId == RemoteAPICmd.REQUEST_V1_MAKE_PAY_RECORD){
            noticeOffline();
        }
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_order_now){
            if(mResourceInfo!= null) {
                if(checkUserInput()) {
                    if (Float.parseFloat(mResourceInfo.getDeposit()) > 0.0) {
                        executeOrderAction();
                    } else {
                        executeOrderActionNoDeposit();
                    }
                }
            }
        }
        else if(v.getId() == R.id.tv_need_hd){
            if(mHDContain){
                String mark = mOrderMark.getText().toString();
                if(mark.contains("需要回单")){
                    mark = mark.replace("需要回单", "");
                    mOrderMark.setText(mark);
                }
                mHDContain = false;
                mNeedHD.setBackgroundResource(R.drawable.rounded_edittext);
            }
            else{
                String mark = mOrderMark.getText().toString();
                mark += "需要回单";
                mOrderMark.setText(mark);
                mHDContain = true;
                mNeedHD.setBackgroundResource(R.drawable.rounded_button);
            }
        }
        else if(v.getId() == R.id.tv_need_fp){
            if(mFPContain){
                String mark = mOrderMark.getText().toString();
                if(mark.contains("需要发票")){
                    mark = mark.replace("需要发票", "");
                    mOrderMark.setText(mark);
                }
                mFPContain = false;
                mNeedFP.setBackgroundResource(R.drawable.rounded_edittext);
            }
            else{
                String mark = mOrderMark.getText().toString();
                mark += "需要发票";
                mOrderMark.setText(mark);
                mFPContain = true;
                mNeedFP.setBackgroundResource(R.drawable.rounded_button);
            }
        }
        else{

        }
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    @Override
    public void onResp(BaseResp baseResp) {
        if (baseResp.getType() == ConstantsAPI.COMMAND_LAUNCH_WX_MINIPROGRAM) {
            WXLaunchMiniProgram.Resp launchMiniProResp = (WXLaunchMiniProgram.Resp)baseResp;
            String extraData = launchMiniProResp.extMsg; //对应小程序组件 <button open-type="launchApp"> 中的 app-parameter 属性
            Log.d(TAG, "extraData: " + extraData);
        }
    }
}